package view.admin;

import controller.SeatController;
import model.Seat;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Comparator;
import java.util.List;

/**
 * 座位管理面板
 */
public class SeatManagementPanel extends JPanel {
    private SeatController seatController;

    private JTable seatTable;
    private DefaultTableModel tableModel;
    private TableRowSorter<DefaultTableModel> tableSorter;
    private JButton addButton;
    private JButton editButton;
    private JButton refreshButton;
    private JComboBox<String> floorFilterComboBox;
    private JComboBox<String> statusFilterComboBox;

    public SeatManagementPanel() {
        this.seatController = new SeatController();

        initComponents();
        setupLayout();
        setupEventListeners();
        refreshData();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        setBackground(new Color(248, 250, 252));

        // 表格列名
        String[] columnNames = { "座位ID", "座位号", "区域", "状态", "电脑", "电源", "设备信息" };
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        seatTable = new JTable(tableModel);
        seatTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        seatTable.setRowHeight(30);

        // 添加排序功能
        tableSorter = new TableRowSorter<>(tableModel);
        seatTable.setRowSorter(tableSorter);

        // 配置表头样式
        JTableHeader header = seatTable.getTableHeader();
        header.setFont(new Font("Microsoft YaHei", Font.BOLD, 12));
        header.setBackground(new Color(243, 244, 246));
        header.setForeground(new Color(75, 85, 99));
        header.setReorderingAllowed(false);

        // 美化表格
        styleTable(seatTable);

        // 简化排序配置，让系统自动处理
        // setupColumnComparators();

        // 设置列宽
        seatTable.getColumnModel().getColumn(0).setPreferredWidth(80); // 座位ID
        seatTable.getColumnModel().getColumn(1).setPreferredWidth(100); // 座位号
        seatTable.getColumnModel().getColumn(2).setPreferredWidth(150); // 区域
        seatTable.getColumnModel().getColumn(3).setPreferredWidth(80); // 状态
        seatTable.getColumnModel().getColumn(4).setPreferredWidth(60); // 电脑
        seatTable.getColumnModel().getColumn(5).setPreferredWidth(60); // 电源
        seatTable.getColumnModel().getColumn(6).setPreferredWidth(200); // 设备信息（加宽）

        // 按钮
        addButton = new JButton("添加楼层");
        editButton = new JButton("编辑座位");
        refreshButton = new JButton("刷新");

        // 美化按钮
        styleButton(addButton, new Color(34, 197, 94), Color.WHITE);
        styleButton(editButton, new Color(59, 130, 246), Color.WHITE);
        styleButton(refreshButton, new Color(59, 130, 246), Color.WHITE);

        editButton.setEnabled(false);

        // 筛选器
        floorFilterComboBox = new JComboBox<>();
        floorFilterComboBox.addItem("全部区域");
        // 动态加载区域数据
        loadAreaOptions();

        statusFilterComboBox = new JComboBox<>();
        statusFilterComboBox.addItem("全部状态");
        statusFilterComboBox.addItem("可用");
        statusFilterComboBox.addItem("已预约");
        statusFilterComboBox.addItem("维护中");

        // 美化组合框
        styleComboBox(floorFilterComboBox);
        styleComboBox(statusFilterComboBox);
    }

    private void setupLayout() {
        // 现代化顶部工具栏
        JPanel toolPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        toolPanel.setBackground(new Color(255, 255, 255));
        toolPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JLabel floorLabel = createStyledLabel("区域:");
        toolPanel.add(floorLabel);
        toolPanel.add(floorFilterComboBox);
        toolPanel.add(Box.createHorizontalStrut(15));

        JLabel statusLabel = createStyledLabel("状态:");
        toolPanel.add(statusLabel);
        toolPanel.add(statusFilterComboBox);
        toolPanel.add(Box.createHorizontalStrut(25));

        toolPanel.add(refreshButton);
        toolPanel.add(Box.createHorizontalStrut(10));
        toolPanel.add(addButton);
        toolPanel.add(editButton);

        // 现代化表格面板
        JScrollPane scrollPane = new JScrollPane(seatTable);
        scrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(0, 0, 0, 0)));
        scrollPane.getViewport().setBackground(new Color(255, 255, 255));

        // 现代化底部统计面板
        JPanel statsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        statsPanel.setBackground(new Color(255, 255, 255));
        statsPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JLabel totalSeatsLabel = createStyledLabel("总座位数: 0");
        JLabel availableSeatsLabel = createStyledLabel("可用座位: 0");
        JLabel reservedSeatsLabel = createStyledLabel("已预约: 0");
        JLabel maintenanceSeatsLabel = createStyledLabel("维护中: 0");

        statsPanel.add(totalSeatsLabel);
        statsPanel.add(Box.createHorizontalStrut(25));
        statsPanel.add(availableSeatsLabel);
        statsPanel.add(Box.createHorizontalStrut(25));
        statsPanel.add(reservedSeatsLabel);
        statsPanel.add(Box.createHorizontalStrut(25));
        statsPanel.add(maintenanceSeatsLabel);

        add(toolPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
        add(statsPanel, BorderLayout.SOUTH);
    }

    private void setupEventListeners() {
        refreshButton.addActionListener(_ -> refreshData());

        floorFilterComboBox.addActionListener(_ -> refreshData());
        statusFilterComboBox.addActionListener(_ -> refreshData());

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                openFloorDialog();
            }
        });

        editButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                editSelectedSeat();
            }
        });

        // 表格选择事件
        seatTable.getSelectionModel().addListSelectionListener(e -> {
            if (!e.getValueIsAdjusting()) {
                boolean hasSelection = seatTable.getSelectedRow() >= 0;
                editButton.setEnabled(hasSelection);
            }
        });
    }

    public void refreshData() {
        try {
            // 获取筛选条件
            String floorFilter = (String) floorFilterComboBox.getSelectedItem();
            String statusFilter = (String) statusFilterComboBox.getSelectedItem();

            String areaFilter = floorFilter.equals("全部区域") ? null : floorFilter;

            int status = -1;
            if (!statusFilter.equals("全部状态")) {
                switch (statusFilter) {
                    case "可用":
                        status = 0;
                        break;
                    case "已预约":
                        status = 1;
                        break;
                    case "维护中":
                        status = 2;
                        break;
                }
            }

            // 使用新的实时状态查询方法
            List<Seat> seats = seatController.getFilteredSeatsWithRealTimeStatus(areaFilter, status);

            // 清空表格
            tableModel.setRowCount(0);

            // 填充数据
            for (Seat seat : seats) {
                Object[] row = {
                        seat.getSeatId(),
                        seat.getSeatNumber(),
                        seat.getArea(),
                        seat.getStatusText(),
                        seat.isHasComputer() ? "有" : "无",
                        seat.isHasPowerSocket() ? "有" : "无",
                        seat.getEquipment()
                };
                tableModel.addRow(row);
            }

            // 更新统计信息
            updateStatistics(seats);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载座位信息失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void updateStatistics(List<Seat> seats) {
        int total = seats.size();
        int available = 0;
        int reserved = 0;
        int maintenance = 0;

        for (Seat seat : seats) {
            switch (seat.getStatus()) {
                case 0:
                    available++;
                    break;
                case 1:
                    reserved++;
                    break;
                case 2:
                    maintenance++;
                    break;
            }
        }

        // 更新底部统计标签
        Component[] components = ((JPanel) getComponent(2)).getComponents();
        if (components.length >= 7) {
            ((JLabel) components[0]).setText("总座位数: " + total);
            ((JLabel) components[2]).setText("可用座位: " + available);
            ((JLabel) components[4]).setText("已预约: " + reserved);
            ((JLabel) components[6]).setText("维护中: " + maintenance);
        }
    }

    private void openSeatDialog(Seat seat) {
        SeatEditDialog dialog = new SeatEditDialog((JFrame) SwingUtilities.getWindowAncestor(this), seat);
        dialog.setVisible(true);

        if (dialog.isConfirmed()) {
            refreshData();
        }
    }

    private void openFloorDialog() {
        FloorAddDialog dialog = new FloorAddDialog((JFrame) SwingUtilities.getWindowAncestor(this));
        dialog.setVisible(true);

        if (dialog.isConfirmed()) {
            refreshData();
        }
    }

    private void editSelectedSeat() {
        int selectedRow = seatTable.getSelectedRow();
        if (selectedRow < 0)
            return;

        try {
            int seatId = (Integer) tableModel.getValueAt(selectedRow, 0);
            Seat seat = seatController.getSeatById(seatId);
            openSeatDialog(seat);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "获取座位信息失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 创建样式化标签
     */
    private JLabel createStyledLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        label.setForeground(new Color(75, 85, 99));
        return label;
    }

    /**
     * 美化表格样式
     */
    private void styleTable(JTable table) {
        table.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        table.setBackground(new Color(255, 255, 255));
        table.setForeground(new Color(55, 65, 81));
        table.setGridColor(new Color(229, 231, 235));
        table.setSelectionBackground(new Color(219, 234, 254));
        table.setSelectionForeground(new Color(30, 64, 175));

        // 表头样式
        table.getTableHeader().setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        table.getTableHeader().setBackground(new Color(249, 250, 251));
        table.getTableHeader().setForeground(new Color(55, 65, 81));
        table.getTableHeader().setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(229, 231, 235)));
    }

    /**
     * 美化按钮样式
     */
    private void styleButton(JButton button, Color backgroundColor, Color textColor) {
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBackground(backgroundColor);
        button.setForeground(textColor);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(backgroundColor.darker(), 1),
                BorderFactory.createEmptyBorder(8, 16, 8, 16)));
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    /**
     * 加载区域选项
     */
    private void loadAreaOptions() {
        try {
            List<String> areas = seatController.getAllAreas();
            for (String area : areas) {
                floorFilterComboBox.addItem(area);
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载区域选项失败：" + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 美化组合框样式
     */
    private void styleComboBox(JComboBox<String> comboBox) {
        comboBox.setPreferredSize(new Dimension(120, 30));
        comboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        comboBox.setBackground(new Color(255, 255, 255));
        comboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(4, 8, 4, 8)));
    }

    /**
     * 设置表格列的排序比较器
     */
    private void setupColumnComparators() {
        // 座位ID列 - 数字排序
        tableSorter.setComparator(0, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                try {
                    return Integer.compare(Integer.parseInt(o1), Integer.parseInt(o2));
                } catch (NumberFormatException e) {
                    return o1.compareTo(o2);
                }
            }
        });

        // 座位号列 - 自然排序
        tableSorter.setComparator(1, String.CASE_INSENSITIVE_ORDER);

        // 区域列 - 字符串排序
        tableSorter.setComparator(2, String.CASE_INSENSITIVE_ORDER);

        // 状态列 - 状态优先级排序
        tableSorter.setComparator(3, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return getSeatStatusPriority(o1) - getSeatStatusPriority(o2);
            }

            private int getSeatStatusPriority(String status) {
                switch (status) {
                    case "可用":
                        return 1;
                    case "已预约":
                        return 2;
                    case "维护中":
                        return 3;
                    default:
                        return 999;
                }
            }
        });

        // 电脑列 - 布尔排序
        tableSorter.setComparator(4, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                boolean b1 = "有".equals(o1);
                boolean b2 = "有".equals(o2);
                return Boolean.compare(b2, b1); // 有电脑的排在前面
            }
        });

        // 电源列 - 布尔排序
        tableSorter.setComparator(5, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                boolean b1 = "有".equals(o1);
                boolean b2 = "有".equals(o2);
                return Boolean.compare(b2, b1); // 有电源的排在前面
            }
        });

        // 设备信息列 - 字符串排序
        tableSorter.setComparator(6, String.CASE_INSENSITIVE_ORDER);
    }
}
